﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HousingInfo.Library;
using System.IO;

namespace NEWS.Admin
{
    public partial class Edit_AddNewsBussiness : System.Web.UI.Page
    {
        private static string mode = null, modeapprove = null, modeview = null;
        private static NewsBussinessBO newsbussinessbo;
        private static string _fileImageName;
        private static bool retun = true;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                mode = Request.QueryString["Mode"];
                modeapprove = Request.QueryString["approve"];
                modeview = Request.QueryString["view"];
                if (mode != null)
                {
                    //quy dinh an hien cac truong
                    pn_iduser.Visible = false;
                    pn_songaymuondang.Visible = false;
                    pn_giahan.Visible = false;
                    newsbussinessbo = NewsBussinessBO.GetNewsBussinessBO(Convert.ToInt32(mode));
                    if (newsbussinessbo.IsExtension == false)
                    {
                        pn_ngaygiahagannhat.Visible = false;
                    }
                    //lay option
                    OptionBO optionbo;
                    optionbo = OptionBO.GetNameOptionBO("SoLanGiaHanTinDoanhNghiep");
                    if (modeapprove == "true")
                    {
                        pn_active.Visible = false;
                        btbupdate.Visible = false;
                        btnapprove.Visible = true;
                        btnapprove.Focus();
                    }
                    if (newsbussinessbo.ExpireDate < DateTime.Now && Convert.ToInt32(optionbo.OptionValue) > newsbussinessbo.NumExtension)
                    {
                        pn_checkgiahan.Visible = true;
                        btbupdate.Visible = false;
                        lblsolancon.Text = (Convert.ToInt32(optionbo.OptionValue) - newsbussinessbo.NumExtension).ToString();                        
                    }
                    if (newsbussinessbo.ExpireDate < DateTime.Now && Convert.ToInt32(optionbo.OptionValue) <= newsbussinessbo.NumExtension)
                    {
                        pn_checkgiahan.Visible = true;
                        lblthongbaohethan.Text = " Tin này đã hết hạn và hết quyền gia hạn  ";
                        lbtgiahan.Text = "Click Vào Đây Đăng Tin Mới";
                        btbupdate.Visible = false;
                    }
                    if (newsbussinessbo.UrlImage != "")
                    {
                        FileUpload_Image.Visible = false;
                        lbthuy.Visible = false;
                        txtimage.Visible = true;
                        txtimage.Text = newsbussinessbo.UrlImage;
                        txtimage.ReadOnly = true;
                        lbtthaydoi.Visible = true;
                    }
                    if (modeview == "true")
                    {
                        btngiahan.Visible = false;
                        btbupdate.Visible = false;
                    }
                    txtnewsbussinessid.Text = newsbussinessbo.NewsBussinessID.ToString();
                    txtusername.Text = newsbussinessbo.UserName;
                    txtbussinessname.Text = newsbussinessbo.BussinessName;
                    txtbussinessaddress.Text = newsbussinessbo.BussinessAddress;
                    txtwebsite.Text = newsbussinessbo.BussinessWebsite;
                    txtphone.Text = newsbussinessbo.BussinessPhone;
                    txtbussinesscontent.Text = newsbussinessbo.BussinessContent;
                    txtemail.Text = newsbussinessbo.Email;
                    lbldatecreated.Text = Convert.ToDateTime(newsbussinessbo.CreatedDate).ToString("dd/MM/yyyy");
                    txtexpiredate.Text = Convert.ToDateTime(newsbussinessbo.ExpireDate).ToString("dd/MM/yyyy");
                    txtdateextension.Text = Convert.ToDateTime(newsbussinessbo.ExtensionDate).ToString("dd/MM/yyyy");
                    //lbldatepost.Text = newsbussinessbo.PostDate.ToString();
                    lbldateupdate.Text = Convert.ToDateTime(newsbussinessbo.UpdatedDate).ToString("dd/MM/yyyy");
                    txtnumextention.Text = newsbussinessbo.NumExtension.ToString();
                    txtsolandagiahan.Text = newsbussinessbo.NumExtension.ToString();
                    isactive.Checked = newsbussinessbo.IsActive;
                }
                else
                {
                    pn_iduser.Visible = false;
                    pn_suatin.Visible = false;
                    pn_giahan.Visible = false;
                    pn_songaymuondang.Visible = true;
                    lblheader.Text = "Đăng Tin Doanh Nghiệp";
                    btbupdate.Text = "Thêm";
                }
            }
        }

        protected void btbupdate_Click(object sender, EventArgs e)
        {
            if (mode != null)
            {
                //thuc hien code cho update
                int newsbussinessid = Convert.ToInt32(txtnewsbussinessid.Text);
                newsbussinessbo = NewsBussinessBO.GetNewsBussinessBO(newsbussinessid);
                newsbussinessbo.BussinessName = txtbussinessname.Text;
                newsbussinessbo.BussinessPhone = txtphone.Text;
                newsbussinessbo.BussinessAddress = txtbussinessaddress.Text;
                newsbussinessbo.BussinessWebsite = txtwebsite.Text;
                newsbussinessbo.BussinessContent = txtbussinesscontent.Text;
                newsbussinessbo.Email = txtemail.Text;
                newsbussinessbo.UpdatedDate = DateTime.Now;
                newsbussinessbo.IsActive = isactive.Checked;
                if (FileUpload_Image.Visible == true)
                {
                    deleteExitsImage(newsbussinessbo.UrlImage);
                    if (FileUpload_Image.FileName.Length > 0)
                    {
                        postImage(FileUpload_Image);
                        if (retun == false) return;
                    }
                    else newsbussinessbo.UrlImage = "";
                }
                //cap nhat khi co gia han
                if (pn_giahan.Visible == true)
                {
                    newsbussinessbo.IsExtension = true;
                    newsbussinessbo.NumExtension += 1;
                    txtnumextention.Text = newsbussinessbo.NumExtension.ToString();
                    newsbussinessbo.ExpireDate = DateTime.Now.AddDays(double.Parse(drlgiahan.SelectedValue));
                    newsbussinessbo.PostDate = DateTime.Now;
                    txtexpiredate.Text = DateTime.Now.AddDays(double.Parse(drlgiahan.SelectedValue)).ToString();
                    newsbussinessbo.ExtensionDate = DateTime.Now;
                    try
                    {
                        newsbussinessbo.Save();
                        pn_giahan.Visible = false;
                        pn_checkgiahan.Visible = false;
                        lbldateupdate.Text = DateTime.Now.ToString();
                        message.Text = "Cập nhật thành công !";
                    }
                    catch
                    {
                        message.Text = "Cập nhật thất bại !";
                    }

                }
                else
                {
                    try
                    {
                        newsbussinessbo.Save();
                        //if (newsbussinessbo.ExpireDate <= DateTime.Now)
                        //{

                        //}
                        lbldateupdate.Text = DateTime.Now.ToString();
                        if (modeapprove == "true")
                        {
                            if (isactive.Checked == true)
                                Response.Redirect("NewsBussiness.aspx?Save=Complete&approve=true");
                            else Response.Redirect("NewsBussiness.aspx?approve=true");
                        }
                        else Response.Redirect("NewsBussiness.aspx?Save=Update"); 
                    }
                    catch
                    {
                        message.Text = "Cập nhật thất bại !";
                    }
                }
            }
            else
            {
                //Them moi tin doanh nghiep
                newsbussinessbo = NewsBussinessBO.NewNewsBussinessBO();
                newsbussinessbo.UserName = Session["UserNameAdmin"].ToString();
                newsbussinessbo.BussinessName = txtbussinessname.Text;
                if (FileUpload_Image.FileName.Length > 0)
                {
                    postImage(FileUpload_Image);
                    if (retun == false) return;
                }
                else newsbussinessbo.UrlImage = "";
                newsbussinessbo.BussinessAddress = txtbussinessaddress.Text;
                newsbussinessbo.BussinessWebsite = txtwebsite.Text;
                newsbussinessbo.BussinessPhone = txtphone.Text;
                newsbussinessbo.BussinessContent = txtbussinesscontent.Text;
                newsbussinessbo.Email = txtemail.Text;
                newsbussinessbo.IsExtension = false;
                newsbussinessbo.IsActive = isactive.Checked;
                newsbussinessbo.CreatedDate = DateTime.Now;
                newsbussinessbo.UpdatedDate = DateTime.Now;
                newsbussinessbo.NumExtension = 0;
                newsbussinessbo.PostDate = DateTime.Now;
                newsbussinessbo.ExpireDate = DateTime.Now.AddDays(double.Parse(drlnumexpire.SelectedValue));
                try
                {
                    newsbussinessbo.Save();                    
                    message.Text = "Thêm thành công !";                    
                    //resetControls(); dua tat ca cac textbox ve null
                    Response.Redirect("NewsBussiness.aspx?Save=Complete");
                }
                catch
                {
                    message.Text = "Thêm thất bại !";
                    return;
                }
            }
        }

        private void postImage(FileUpload filename)
        {
            try
            {
                if (filename.HasFile)
                {
                    if (filename.FileBytes.Length < 512000)
                    {
                        _fileImageName = filename.FileName.Replace(" ", "_");

                        string formatFile = Path.GetExtension(_fileImageName);
                        //kiem tra dinh dang cho phep upload
                        if (formatFile.Equals(".jpg") || formatFile.Equals(".gif") || formatFile.Equals(".png") || formatFile.Equals(".JPG") || formatFile.Equals(".GIF") || formatFile.Equals(".PNG"))
                        {
                            //kiem tra file da ton tai
                            string filePath = HttpContext.Current.Server.MapPath("~/TotalUpload/ImagesTotal/" + _fileImageName);
                            if (File.Exists(filePath))
                            {
                                //neu ton tai thi doi ten
                                _fileImageName = ImageFileName(_fileImageName);
                            }
                            //thuc hien luu file
                            try
                            {
                                filename.SaveAs(Server.MapPath("~/TotalUpload/ImagesTotal/" + _fileImageName));
                                //deleteExitsImage(txtlink.Text);
                                //txtlink.Text = _fileImageName;
                                try
                                {
                                    newsbussinessbo.UrlImage = _fileImageName;
                                }
                                catch
                                {
                                    newsbussinessbo.UrlImage = "";
                                }
                            }
                            catch (Exception)
                            {
                                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Có một số vấn đề xả ra trong khi lưu. Xin hay thử lại.')", true);
                                retun = false;
                                return;
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chỉ được upload các định dạng ảnh (.jpg , .gif, .png)')", true);
                            retun = false;
                            return;
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Kích thước ảnh không quá 500Kb.')", true);
                        retun = false;
                        return;
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chưa chọn hỉnh ảnh đại diện. !')", true);
                    retun = false;
                    return;
                }
            }
            catch { }
        }

        private static string ImageFileName(string fileName)
        {
            Random r = new Random();
            return r.Next(0, 10000).ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + fileName;
        }

        private void deleteExitsImage(string filedelete)
        {
            try
            {
                var pathFileImage = Server.MapPath("~/TotalUpload/ImagesTotal/" + filedelete);
                FileInfo fileInfo;
                if (File.Exists(pathFileImage))
                {
                    fileInfo = new FileInfo(pathFileImage);
                    fileInfo.Delete();
                }
            }
            catch
            {
            }
        }

        protected void btnback_Click(object sender, EventArgs e)
        {
            if(modeapprove == "true")
                Response.Redirect("NewsBussiness.aspx?approve=true");
            else Response.Redirect("NewsBussiness.aspx");
        }

        protected void lbtgiahan_Click(object sender, EventArgs e)
        {
            if (lbtgiahan.Text == "Click Vào Đây Đăng Tin Mới")
            {
                Response.Redirect("Edit_AddNewsBussiness.aspx");
            }
            else
            {
                pn_giahan.Visible = true;
                btbupdate.Visible = false;
                btngiahan.Visible = true;
                lbtgiahan.Focus();
            }
        }

        protected void lbthuy_Click(object sender, EventArgs e)
        {
            FileUpload_Image.Visible = false;
            txtimage.Visible = true;
            lbtthaydoi.Visible = true;
            lbthuy.Visible = false;
        }

        protected void lbtthaydoi_Click(object sender, EventArgs e)
        {
            txtimage.Visible = false;
            lbtthaydoi.Visible = false;
            FileUpload_Image.Visible = true;
            lbthuy.Visible = true;
        }

        protected void btngiahan_Click(object sender, EventArgs e)
        {
            NewsBussinessBO nbbo;
            nbbo = NewsBussinessBO.GetNewsBussinessBO(int.Parse(mode));
            nbbo.IsExtension = true;
            nbbo.NumExtension += 1;
            txtnumextention.Text = nbbo.NumExtension.ToString();
            nbbo.ExpireDate = DateTime.Now.AddDays(double.Parse(drlgiahan.SelectedValue));
            nbbo.PostDate = DateTime.Now;
            txtexpiredate.Text = DateTime.Now.AddDays(double.Parse(drlgiahan.SelectedValue)).ToString();
            nbbo.ExtensionDate = DateTime.Now;
            try
            {
                nbbo.Save();
                pn_giahan.Visible = false;
                pn_checkgiahan.Visible = false;
                lbldateupdate.Text = DateTime.Now.ToString();
                message.Text = "Gia Hạn thành công !";
                Response.Redirect("NewsBussiness.aspx?Save=Exten");
            }
            catch
            {
                message.Text = "Gia Hạn thất bại !";
            }
        }

        protected void btnapprove_Click(object sender, EventArgs e)
        {
            NewsBussinessBO nbbo;
            nbbo = NewsBussinessBO.GetNewsBussinessBO(int.Parse(mode));
            nbbo.IsActive = true;
            try
            {
                nbbo.Save();
                Response.Redirect("NewsBussiness.aspx?Save=Complete&approve=true");
            }
            catch { message.Text = "Duyệt tin thất bại!"; }
        }
    }
}
